package com.yupi.springbootinit.utils;/*
@author name
@data 2025/2/15-16:08
*/


import cn.hutool.core.util.StrUtil;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.ThrowUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GetSql {
    public static String createSql(String chartId, String csvData) {

        // 验证输入数据
        if (StrUtil.isBlank(chartId) || StrUtil.isBlank(csvData)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR,"参数错误");
        }
        String[] oneStr = csvData.split("\n");
        if (oneStr.length == 0) {
            return null;
        }
        String[] colName = oneStr[0].split(","); // 假设第一行是表头

        // 初始化 fieldBuilder，并添加 id 字段
        StringBuilder fieldBuilder = new StringBuilder();
        fieldBuilder.append("`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"); // 添加 id 字段
        // 添加其他字段
        for (int i = 0; i < colName.length; i++) {
            fieldBuilder.append(", `").append(colName[i]).append("`").append(" varchar(128) null");
        }

        String sql = String.format("CREATE TABLE IF NOT EXISTS %s (%s) collate = utf8mb4_unicode_ci;", "chart_"+chartId, fieldBuilder);
        System.out.println(sql);
        return sql;
    }

    public static List<String> insertSql(String chartId,String csvData) {

        //INSERT INTO chart_4 (id,`日期`, `用户数`) VALUES ('1','1号', '10');
        // 验证输入数据
        if (StrUtil.isBlank(chartId) || StrUtil.isBlank(csvData)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR,"参数错误");
        }
        List<String> sqlList = new ArrayList();
        String[] splitStr = csvData.split("\n");
        String[] titles = splitStr[0].split(",");
        //获取表字段
        StringBuilder titleStr = new StringBuilder();
        for (int i = 0; i < titles.length; i++) {
            titleStr.append("`");
            titleStr.append(titles[i]);
            titleStr.append("`");
            if (i < titles.length - 1) {
                titleStr.append(",");
            }
        }
        //获取表内容
        StringBuilder contentStr = new StringBuilder();
        for (int i = 1; i < splitStr.length; i++) {
            contentStr.setLength(0);
            String[] content = splitStr[i].split(",");
            for (int j = 0; j < content.length; j++) {
                contentStr.append("'");
                contentStr.append(content[j]);
                contentStr.append("'");
                if (j < content.length - 1) {
                    contentStr.append(",");
                }
            }
            String sql = String.format("insert into chart_%s (%s) value (%s)", chartId,titleStr, contentStr);
            sqlList.add(sql);
            System.out.println(sqlList.toString());
        }
        return sqlList;
    }

    public static String[] buildUpdateSQL(String tableName, List<Map<String, String>> maps) {
        String[] sqlStr = new String[maps.size()];

        for (int i = 0; i < maps.size(); i++) {
            Map<String, String> map = maps.get(i);
            StringBuilder builder = new StringBuilder();
            builder.append("UPDATE ").append(tableName).append(" SET ");

            boolean hasFields = false;
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String columnName = entry.getKey().trim();
                String value = entry.getValue();
                if (!"id".equals(columnName)) {
                    builder.append("`").append(columnName).append("` = '").append(value).append("', ");
                    hasFields = true;
                }
            }

            // 移除末尾逗号和空格（仅当有字段时）
            if (hasFields) {
                builder.setLength(builder.length() - 2);
            }

            // 添加WHERE条件
            builder.append(" WHERE id = '").append(map.get("id")).append("';");

            // 存储到数组
            sqlStr[i] = builder.toString();
        }

        // 打印所有SQL
        System.out.println("===================将要执行的SQL===================");
        for (String sql : sqlStr) {
            System.out.println(sql);
        }
        return sqlStr;
    }
}